package com.vpen.websocket.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/8/31 17:37
 */
@Component
@Slf4j
@ServerEndpoint("/hello/{uid}")
public class HelloController {

    private static final ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) throws IOException {
        log.debug("uid:{},session:{},建立连接", uid, session);
        sessionPools.put(uid, session);
        broadcast(uid + "来了");
    }

    @OnClose
    public void onClose(@PathParam(value = "uid") String uid) throws IOException {
        sessionPools.remove(uid);
        broadcast(uid + "走了");
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        log.debug("收到消息：{}", message);
        broadcast(message);
    }


    @OnError
    public void onError(Session session, Throwable throwable) {
        log.debug("{}", throwable.getMessage());
    }

    public void sendMessage(Session session, String message) throws IOException {
        log.debug("发送");
        session.getBasicRemote().sendText(message);
    }


    public void sendToUser(String uid, String message) throws IOException {
        Session session = sessionPools.get(uid);
        sendMessage(session, message);
    }


    public void broadcast(String message) throws IOException {
        for (Session session : sessionPools.values()) {
            sendMessage(session, message);
        }
    }
}
